package com.haochang.chunkvod.controller.fragment.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseFragment;
import com.haochang.base.BaseListView;
import com.haochang.base.BaseScrollView;
import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.database.order.GoodsInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.controller.adapter.order.OrderAdapter;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.MenuInfo;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.ShopCartData;
import com.haochang.chunkvod.tools.vod.event.EventObserver;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshListView;
import com.haochang.chunkvod.view.vod.activity.AuthorizationDialogActivity;
import com.haochang.chunkvod.view.vod.activity.SingleInputActivity;
import com.haochang.chunkvod.view.vod.menu.MenuLayout;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;

/**
 * @author qintao
 *         created at 2016/6/13 10:38
 *         点餐
 */

public class OrderFragment extends BaseFragment implements EventObserver
{
	private TitleView titleView;
	private BaseEditText et_search;
	private ImageView img_del;
	private ImageView img_to_top;
	private MenuLayout tabSwitcher;
	private BaseScrollView scrollView;
	private PullToRefreshListView listView;
	private OrderAdapter orderAdapter;
	private PullToRefreshListView search_listView;
	private BaseTextView tv_no_data;
	private OrderData orderData;
	private ShopCartData shopCartData;
	private String roomNum;
	private String roomId;
	private String billId;
	private String menuId;
	private String charging_room_type_id;//计费房型id
	private String roomStatus;//房间状态
	private int type;//类型
	private List<MenuInfo> menuInfoList = new ArrayList<MenuInfo>();//菜单信息
	private List<GoodsInfo> goodsInfoList = new ArrayList<GoodsInfo>();//商品列表
	private List<GoodsInfo> searchGoodsInfoList = new ArrayList<GoodsInfo>();//搜索商品列表
	private List<GoodsInfo> goodsDbInfoList = new ArrayList<GoodsInfo>();//已点商品列表--购物车
	private GoodsInfo resultGoodInfo = null;
	private JSONArray goodsArray = null;
	private String deliveryAddress = "";//缓存送餐地址
	/**
	 * 是否为增送模式
	 */
	private boolean is_give = false;
	/**
	 * 是否为增送类别
	 */
	private boolean is_present = false;
	private int is_active = 0;
	/**
	 * 是否第一次提醒
	 */
	private boolean isFirstTip = false;
	private boolean isTokenOut = false;
	private String token = "";
	//private boolean isLocalNeedBillId = true;//去掉桌台买单未离清空原桌台逻辑
	private GoodsInfo bottomInfo = new GoodsInfo();
	private boolean isRefreshData = false;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.activity_order, container, false);
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		EventProxy.addEventListener(this, IEventConstant.EVENT_SHOP_CART);
		initData();
		initView();
	}

	@Override
	public void onViewStateRestored(@Nullable Bundle savedInstanceState)
	{
		super.onViewStateRestored(savedInstanceState);
		isRefreshData = false;
		et_search.setText("");
	}

	private void initData()
	{
		orderData = new OrderData((BaseActivity) getActivity());
		shopCartData = new ShopCartData((BaseActivity) getActivity());
		roomNum = getArguments().getString(IntentKey.ROOM_NUM);
		roomId = getArguments().getString(IntentKey.ROOM_ID);
		billId = getArguments().getString(IntentKey.BILL_ID);
		charging_room_type_id = getArguments().getString(IntentKey.CHARGING_ROOM_TYPE_ID);
		isTokenOut = getArguments().getBoolean(IntentKey.ORDER_TAKEOUT);
		roomStatus = getArguments().getString(IntentKey.ROOM_STATUS);
		type = getArguments().getInt(IntentKey.ROOM_TYPE);
		if (!CollectionUtils.isEmpty(goodsInfoList))
			goodsInfoList.clear();
		if (!CollectionUtils.isEmpty(searchGoodsInfoList))
			searchGoodsInfoList.clear();
	}

	private void initView()
	{
		isRefreshData = true;
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(roomNum).setBackText("主页").setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				getActivity().finish();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				if (is_give)
					list.add("正常模式");
				else
					list.add("赠送模式");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(getActivity(), list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							if (is_give)
								is_give = false;
							else
								is_give = true;
							restoreData(goodsInfoList, searchGoodsInfoList);
							if (TextUtils.isEmpty(et_search.getText().toString()))
							{
								updateMenuOrderNum(true);
							} else
							{
								updateMenuOrderNum(false);
							}
							orderAdapter.setChecked(is_give);
							break;
						case 1:
							((BaseActivity) getActivity()).loginOut();
							break;
						default:
							break;
						}
					}
				});
			}
		});

		et_search = (BaseEditText) findViewById(R.id.et_search);
		et_search.addTextChangedListener(textWatcher);
		img_del = (ImageView) findViewById(R.id.img_del);
		img_del.setOnClickListener(mOnBaseClickListener);
		tabSwitcher = (MenuLayout) findViewById(R.id.tabSwitcher);
		listView = (PullToRefreshListView) findViewById(R.id.listView);
		listView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
		listView.setOnScrollListener(onScrollListener);
		listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<BaseListView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//下拉刷新
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//上拉加载更多
				getListDataByMenuId(menuId, roomId, billId, false, false, false);
			}
		});
		scrollView = (BaseScrollView) findViewById(R.id.scrollView);
		search_listView = (PullToRefreshListView) findViewById(R.id.search_listView);
		search_listView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
		search_listView.setOnScrollListener(onScrollListener);
		search_listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<BaseListView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//下拉刷新
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//上拉加载更多
				getListDataByKeyWord(roomId, searchGoodsInfoList.size() > 0 ? searchGoodsInfoList.size() - 1 : 0);
			}
		});
		tv_no_data = (BaseTextView) findViewById(R.id.tv_no_data);
		img_to_top = (ImageView) findViewById(R.id.img_to_top);
		img_to_top.setOnClickListener(mOnBaseClickListener);
		orderAdapter = new OrderAdapter(this, getActivity(), R.layout.item_order_list_layout, goodsInfoList, isTokenOut);//添加字段是否是外带
		orderAdapter.setChargingRoomTypeId(charging_room_type_id);
		orderAdapter.setChecked(is_give);
		listView.setAdapter(orderAdapter);
		search_listView.setAdapter(orderAdapter);
		search_listView.setVisibility(View.GONE);
		orderData.requestMenu(billId, new OrderData.IMenuListener()
		{
			@Override
			public void onRequestSuccess(List<MenuInfo> list)
			{
				if (!CollectionUtils.isEmpty(list))
				{
					menuInfoList.clear();
					menuInfoList.addAll(list);
					refreshTabSwitcher();
					menuId = menuInfoList.get(0).getMenuId();
					getListDataByMenuId(menuId, roomId, billId, true, false, false);
				}
			}
		});
	}

	/**
	 * 更新菜单里面的已点商品数量以及购物车数量
	 * 前面4个特殊菜单不显示
	 */
	private void updateMenuOrderNum(boolean flag)
	{
		queryGoodsInfosByType(billId);
		if (CollectionUtils.isEmpty(menuInfoList))
			return;
		int totalNum = 0;
		for (int i = 0; i < menuInfoList.size(); i++)
		{
			String menuId = menuInfoList.get(i).getMenuId();
			int num = 0;
			if (!CollectionUtils.isEmpty(goodsDbInfoList))
			{
				for (int j = 0; j < goodsDbInfoList.size(); j++)
				{
					GoodsInfo info = goodsDbInfoList.get(j);
					if (info != null)
					{
						//累加购物车所有商品的总量，只需要累加一次
						//						if (i == 0)
						//							totalNum += info.getOrderNum();
						//分别累加每个菜单的已点商品数
						if (TextUtils.equals(info.getMenuId(), menuId) && info.is_give() == is_give && info.is_present() == is_present)
							num += info.getOrderNum();
					}
				}
			}
			tabSwitcher.setRemindImageAtPos(i, num > 0 ? View.VISIBLE : View.GONE, num);
		}
		totalNum = GoodsInfoDao.getDao().queryGoodsInfoNum(billId);
		EventProxy.notifyEvent(IEventConstant.EVENT_ORDER_SHOP_CART, totalNum);
		compareFoodInfo(flag ? goodsInfoList : searchGoodsInfoList);
	}

	/**
	 * 根据菜单id获取商品数据
	 *
	 * @param menuId      菜单id
	 * @param roomId      房间id
	 * @param billId      账单id
	 * @param isLoading   是否转圈加载
	 * @param fromMenu    是否是从右边菜单获取数据
	 * @param fromRefresh true为下拉刷新 false为上拉加载
	 */
	private void getListDataByMenuId(String menuId, String roomId, String billId, boolean isLoading, boolean fromMenu, boolean fromRefresh)
	{
		if (fromMenu || fromRefresh)
			goodsInfoList.clear();
		orderData.requestOrderFood(menuId, roomId, billId, isLoading, goodsInfoList.size() > 0 ? String.valueOf((goodsInfoList.size() - 1)) : "0",
				new OrderData.IOrderFoodListener()
				{
					@Override
					public void onRequestSuccess(List<GoodsInfo> list, boolean clear, int isActive)
					{
						is_active = isActive;
						if (clear)
							goodsInfoList.clear();
						if (!CollectionUtils.isEmpty(list))
							goodsInfoList.addAll(list);
						if (goodsInfoList.size() > 0)
						{
							if (goodsInfoList.contains(bottomInfo))
								goodsInfoList.remove(bottomInfo);
							goodsInfoList.add(bottomInfo);
						}
						updateMenuOrderNum(TextUtils.isEmpty(et_search.getText().toString()));
						orderAdapter.replaceAll(goodsInfoList);
					}

					@Override
					public void onFinish()
					{
						//当前没关闭 并且 在刷新
						if (getActivity() != null && !getActivity().isFinishing() && listView.isRefreshing())
						{
							//结束
							listView.onRefreshComplete();
						}
					}
				});
	}

	/**
	 * 根据关键字获取商品数据
	 *
	 * @param roomId 房间id
	 * @param offset 偏移量
	 */
	private void getListDataByKeyWord(String roomId, int offset)
	{
		orderData.requestSearchOrderFood(String.valueOf(is_active), charging_room_type_id, et_search.getText().toString().trim(), roomId, billId, false,
				offset + "", new OrderData.IOrderFoodListener()
				{
					@Override
					public void onRequestSuccess(List<GoodsInfo> list, boolean clear, int isActive)
					{
						is_active = isActive;
						if (clear)
							searchGoodsInfoList.clear();
						if (!CollectionUtils.isEmpty(list))
							searchGoodsInfoList.addAll(list);
						if (searchGoodsInfoList.size() > 0)
						{
							tv_no_data.setVisibility(View.GONE);
							search_listView.setVisibility(View.VISIBLE);
							compareFoodInfo(searchGoodsInfoList);
							if (searchGoodsInfoList.contains(bottomInfo))
								searchGoodsInfoList.remove(bottomInfo);
							searchGoodsInfoList.add(bottomInfo);
							orderAdapter.replaceAll(searchGoodsInfoList);
						} else
						{
							tv_no_data.setVisibility(View.VISIBLE);
							search_listView.setVisibility(View.GONE);
						}
					}

					@Override
					public void onFinish()
					{
						if (getActivity() != null && !getActivity().isFinishing() && search_listView.isRefreshing())
						{
							//结束
							search_listView.onRefreshComplete();
						}
					}
				});
	}

	/**
	 * 桌台买单未离下单弹框提示
	 */
	private boolean isDeskPaiedCapacity()
	{
		if (TextUtils.equals(roomStatus, "paied") && type == 1)
			return true;
		else
			return false;
	}

	/**
	 * 刷新菜单
	 */
	private void refreshTabSwitcher()
	{
		for (MenuInfo info : menuInfoList)
		{
			tabSwitcher.addTab(info);
		}
		tabSwitcher.setOnTabChangedListener(new MenuLayout.OnTabChangedListener()
		{
			@Override
			public void onTabChanged(int last, int current, String mId, int is_give)
			{
				menuId = mId;
				if (is_give == 0)
					is_present = false;
				else
					is_present = true;
				orderAdapter.setIsPresent(is_present);
				getListDataByMenuId(mId, roomId, billId, false, true, false);
			}
		});
	}

	private AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener()
	{
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
		{
			if (getScrollY() > 2)
				img_to_top.setVisibility(View.VISIBLE);
			else
				img_to_top.setVisibility(View.GONE);
		}
	};

	/**
	 * 计算当前listView滚动的距离，因距离不确定，用可见条数代替
	 *
	 * @return 返回滚动的条数
	 */
	public int getScrollY()
	{
		int firstVisiblePosition = 0;
		if (TextUtils.isEmpty(et_search.getText().toString().trim()))
		{
			firstVisiblePosition = listView.getRefreshableView().getFirstVisiblePosition();
		} else
		{
			firstVisiblePosition = search_listView.getRefreshableView().getFirstVisiblePosition();
		}
		return firstVisiblePosition;
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.img_del:
				et_search.setText("");
				break;
			case R.id.img_to_top:
				if (TextUtils.isEmpty(et_search.getText().toString().trim()))
					listView.getRefreshableView().smoothScrollToPosition(0);
				else
					search_listView.getRefreshableView().smoothScrollToPosition(0);
				break;
			default:
				break;
			}
		}
	};

	private TextWatcher textWatcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{

		}

		@Override
		public void afterTextChanged(Editable s)
		{
			if (!TextUtils.isEmpty(et_search.getText().toString().trim()))
			{
				img_del.setVisibility(View.VISIBLE);
				scrollView.setVisibility(View.GONE);
				listView.setVisibility(View.GONE);
				getListDataByKeyWord(roomId, 0);
			} else
			{
				img_del.setVisibility(View.GONE);
				tv_no_data.setVisibility(View.GONE);
				search_listView.setVisibility(View.GONE);
				scrollView.setVisibility(View.VISIBLE);
				listView.setVisibility(View.VISIBLE);
				if (isRefreshData)
					refreshData();
			}
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.FLAVOR_REQUEST && resultCode == Activity.RESULT_OK)
		{
			if (data != null)
			{
				resultGoodInfo = (GoodsInfo) data.getSerializableExtra(IntentKey.GOODSINFO);
				deliveryAddress = data.getStringExtra(IntentKey.ORDER_TAKEOUT_ADDRESS);
				goodsArray = null;
				token = "";
				if (is_give)//is_present == 1增送商品取消权限验证,只要增送模式权限验证
					permissionCode();
				//else if (isDeskPaiedCapacity())
				//deskFree();
				else if (TextUtils.isEmpty(billId))
					onPeopleCountClick();
				else
					placeOrder(null, resultGoodInfo, token, isTokenOut ? deliveryAddress : null);
			} else
				refreshData();
		} else if (requestCode == IntentCode.SHOP_CART_REQUEST_PERMISSION && resultCode == Activity.RESULT_OK)
		{
			if (data != null)
				token = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			//if (isDeskPaiedCapacity())
			//deskFree();
			if (TextUtils.isEmpty(billId))
				onPeopleCountClick();
			else
				placeOrder(null, resultGoodInfo, token, isTokenOut ? deliveryAddress : null);
		} else if (requestCode == IntentCode.ORDER_FLAVOR_REQUEST && resultCode == Activity.RESULT_OK)
		{
			if (data != null)
			{
				String goods = data.getStringExtra(IntentKey.GOODSARRAY);
				deliveryAddress = data.getStringExtra(IntentKey.ORDER_TAKEOUT_ADDRESS);
				if (!TextUtils.isEmpty(goods))
					try
					{
						goodsArray = new JSONArray(goods);
						resultGoodInfo = null;
						token = "";
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
				if (is_give)//is_present == 1增送商品取消权限验证,只要增送模式权限验证
					permissionCode();
				//else if (isDeskPaiedCapacity())
				//deskFree();
				else if (TextUtils.isEmpty(billId))
					onPeopleCountClick();
				else
					placeOrder(null, resultGoodInfo, token, isTokenOut ? deliveryAddress : null);
			} else
				refreshData();
		} else if (requestCode == IntentCode.ROOM_PEOPLE_REQUEST && resultCode == Activity.RESULT_OK && data != null)
		{
			String people_count = data.getStringExtra(IntentKey.CUSTOM_DIALOG_CONTENT);
			JSONObject deskInfo = new JSONObject();
			try
			{
				deskInfo.put("desk_id", roomId);
				deskInfo.put("customer_count", people_count);
				placeOrder(deskInfo, resultGoodInfo, token, isTokenOut ? deliveryAddress : null);
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * 与购物车中的数据进行对比，获取已点的商品数量
	 *
	 * @param goodInfoList 商品信息列表
	 */
	private void compareFoodInfo(List<GoodsInfo> goodInfoList)
	{
		if (!CollectionUtils.isEmpty(goodsDbInfoList) && !CollectionUtils.isEmpty(goodInfoList))
		{
			for (int i = 0; i < goodsDbInfoList.size(); i++)
			{
				GoodsInfo orderFood = goodsDbInfoList.get(i);
				for (int j = 0; j < goodInfoList.size(); j++)
				{
					GoodsInfo foodInfo = goodInfoList.get(j);
					if (orderFood.getGoodsId().equals(foodInfo.getGoodsId()) && orderFood.getMenuId().equals(foodInfo.getMenuId())
							&& orderFood.is_give() == is_give && orderFood.is_present() == is_present)
					{
						foodInfo.setOrderNum(orderFood.getOrderNum());
						break;
					}
				}
			}
		}
	}

	/**
	 * 查询购物车商品,整合已点商品数量
	 *
	 * @param billId 账单id
	 */
	private void queryGoodsInfosByType(final String billId)
	{
		List<GoodsInfo> list = GoodsInfoDao.getDao().queryAllFoodInfos(billId);
		if (!CollectionUtils.isEmpty(list))
		{
			goodsDbInfoList.clear();
			goodsDbInfoList.addAll(list);
			if (!isFirstTip)
			{
				for (GoodsInfo goodsInfo : list)
				{
					if (goodsInfo.getGoods_type() == VodConstant.ACTIVE_TYPE)
						if (goodsInfo.getGoods_type() == VodConstant.ACTIVE_TYPE && !TextUtils.isEmpty(goodsInfo.getCharging_room_type_id())
								&& !goodsInfo.getCharging_room_type_id().equals(charging_room_type_id))
						{
							new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText("前往选择")
									.cancelable(true).contentName("购物车中活动因转包后计费房型改变被删除，需重新选择")
									.onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
									{
										@Override
										public void onOnlyCancelClick()
										{
										}

										@Override
										public void onOkClick()
										{
											//删除购物车中的活动
											isFirstTip = true;
											ShoppingCartManager.deleteActiveGoods(billId);
											tabSwitcher.setSelectedTable(2, menuInfoList.get(2).getMenuId(), 0);
										}

										@Override
										public void onCancelClick()
										{
										}
									}).build().show();
							break;
						}
				}
			}
		} else
			goodsDbInfoList = new ArrayList<GoodsInfo>();
	}

	/**
	 * 还原商品已点数量为0
	 */
	private void restoreData(List<GoodsInfo> foodInfos, List<GoodsInfo> searchInfos)
	{
		if (!CollectionUtils.isEmpty(foodInfos))
		{
			for (int j = 0; j < foodInfos.size(); j++)
			{
				GoodsInfo foodInfo = foodInfos.get(j);
				foodInfo.setOrderNum(0);
			}
		}
		if (!CollectionUtils.isEmpty(searchInfos))
		{
			for (int j = 0; j < searchInfos.size(); j++)
			{
				GoodsInfo foodInfo = searchInfos.get(j);
				foodInfo.setOrderNum(0);
			}
		}
	}

	private void refreshData()
	{
		updateMenuOrderNum(TextUtils.isEmpty(et_search.getText().toString()));
		if (TextUtils.isEmpty(et_search.getText().toString().trim()))
			orderAdapter.replaceAll(goodsInfoList);
		else
			orderAdapter.replaceAll(searchGoodsInfoList);
	}

	/**
	 * 权限验证
	 */
	private void permissionCode()
	{
		Intent intent = new Intent(getActivity(), AuthorizationDialogActivity.class);
		if (isTokenOut)
			intent.putExtra(IntentKey.TOKEN_EVENT, "门店POS系统>点餐系统模块>点餐>外带赠送");//传入权限验证事件名
		else
			intent.putExtra(IntentKey.TOKEN_EVENT, "门店POS系统>点餐系统模块>点餐>赠送");//传入权限验证事件名
		intent.putExtra(IntentKey.INTERFACE_NAME, ApiConfig.VOD_TOKEN);//传入接口名字
		startActivityForResult(intent, IntentCode.SHOP_CART_REQUEST_PERMISSION);
	}

	/**
	 * 点击修改顾客人数
	 */
	private void onPeopleCountClick()
	{
		Intent intent1 = new Intent(getActivity(), SingleInputActivity.class);
		intent1.putExtra(IntentKey.CUSTOM_DIALOG_TITLE, "人数");
		intent1.putExtra(IntentKey.BTN_SURE, "确定");
		intent1.putExtra(IntentKey.BTN_CANCEL, "取消");
		intent1.putExtra(IntentKey.ACTIVITY_ENUM, SingleInputActivity.ActivityEnum.ROOM_NUMBERS);
		startActivityForResult(intent1, IntentCode.ROOM_PEOPLE_REQUEST);
	}

	/**
	 * 桌台下单成功之后把当前数据源的账单id一一赋值
	 */
	private void upDateBillIdForGoodsInfo()
	{
		if (!TextUtils.isEmpty(billId))
		{
			if (!CollectionUtils.isEmpty(goodsInfoList))
				for (int i = 0; i < goodsInfoList.size(); i++)
				{
					GoodsInfo goodsInfo = goodsInfoList.get(i);
					goodsInfo.setBillId(billId);
				}
			if (!CollectionUtils.isEmpty(searchGoodsInfoList))
				for (int i = 0; i < searchGoodsInfoList.size(); i++)
				{
					GoodsInfo goodsInfo = searchGoodsInfoList.get(i);
					goodsInfo.setBillId(billId);
				}
		}
	}

	/**
	 * 桌台下单成功之后如果数据库之前加入了账单id为空的数据把数据库的商品信息的账单id一一赋值
	 */
	private void upDateBillIdForDBGoodsInfo()
	{
		if (!TextUtils.isEmpty(billId))
		{
			List<GoodsInfo> list = GoodsInfoDao.getDao().queryBuilderAll(GoodsInfo.class, "bill_id", "");
			if (!CollectionUtils.isEmpty(list))
			{
				for (int i = 0; i < list.size(); i++)
				{
					GoodsInfo goodsInfo = list.get(i);
					goodsInfo.setBillId(billId);
				}
				try
				{
					GoodsInfoDao.getDao().updateAll(GoodsInfo.class, list);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 单品下单
	 *
	 * @param address  外带地址
	 * @param goodInfo 商品信息
	 * @param token    增送验证token
	 */
	private void placeOrder(JSONObject deskInfo, GoodsInfo goodInfo, String token, String address)
	{
		shopCartData.requestShopCartGoods(deskInfo, roomId, billId, address, null == goodInfo ? goodsArray : ShoppingCartManager.getGoodsArrayByType(goodInfo),
				token, 1, new ShopCartData.IShopCartGoodsListener()
				{
					@Override
					public void onRequestSuccess(String msg, String bill_id)
					{
						ToastUtils.showText(getActivity(), "下单成功");
						if (!TextUtils.isEmpty(bill_id))
						{
							billId = bill_id;
							//							if (type == 1)//桌台
							//							{
							//								roomStatus = "using";
							//								EventProxy.notifyEvent(IEventConstant.EVENT_DESK_STATUS, roomStatus, billId);
							//							}
							upDateBillIdForGoodsInfo();
							upDateBillIdForDBGoodsInfo();
						}
						if (!TextUtils.isEmpty(msg))
						{
							new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.ONLY_TOAST).cancelable(true)
									.contentName("已为您自动添加以下优惠活动：" + msg).onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
									{
										@Override
										public void onOnlyCancelClick()
										{
										}

										@Override
										public void onOkClick()
										{
										}

										@Override
										public void onCancelClick()
										{
										}
									}).build().show();
						}
					}

					@Override
					public void onFail(int errno, String errMsg)
					{
						ToastUtils.showText(getActivity(), errMsg);
						if (errno == 4202 || errno == 4216)//账单已完成，不能点餐
						{
							ShoppingCartManager.clearGoods(billId);
						}
					}
				});
	}

	/**
	 * 桌台转换为空台
	 */
	private void deskFree()
	{
		new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.DOUBLE).cancelable(true).contentName("是否要清空原桌台?").btnNegativeText("否")
				.btnNeutralText("是").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
				{
					@Override
					public void onOnlyCancelClick()
					{
					}

					@Override
					public void onOkClick()
					{
						orderData.requestDeskFree(roomId, billId, new OrderData.IDeskFreeListener()
						{
							@Override
							public void onRequestSuccess()
							{
								//成功之后改变桌台状态
								//isLocalNeedBillId = true;
								billId = "";
								roomStatus = "empty";
								EventProxy.notifyEvent(IEventConstant.EVENT_DESK_STATUS, roomStatus, billId);
								onPeopleCountClick();
							}

							@Override
							public void onFail(int errno, String errMsg)
							{
								if (!TextUtils.isEmpty(errMsg))
									ToastUtils.showText(getActivity(), errMsg);
							}
						});
					}

					@Override
					public void onCancelClick()
					{
						//isLocalNeedBillId = false;
						onPeopleCountClick();
					}
				}).build().show();
	}

	@Override
	public void onDestroy()
	{
		EventProxy.removeEventListener(IEventConstant.EVENT_SHOP_CART, this);
		super.onDestroy();
	}

	@Override
	public void onNotify(Object sender, int eventId, Object... args)
	{
		switch (eventId)
		{
		case IEventConstant.EVENT_SHOP_CART:
			restoreData(goodsInfoList, searchGoodsInfoList);
			refreshData();
			break;
		default:
			break;
		}
	}
}
